package com.sjgtw.web.util;

import android.media.AudioManager;
import android.media.MediaPlayer;

import com.zhipu.android.MainApplication;

import java.io.File;
import java.io.IOException;

/**
 * @file        MediaPlayHelper.java
 * @function    媒体播放器管理器
 * @author      樊夏阳
 * @date        2015-12-5
 * @copyright   Copyright(c) 2015 www.sjgtw.com All rights reserved.
 */
public class MediaPlayHelper {

    private static MediaPlayer mediaPlayer;

    private static boolean isPause;

    /*
    * @function     播放音乐
    * */
    public static void playSound(File soundFile,
                                 MediaPlayer.OnCompletionListener onCompletionListener){
        if (mediaPlayer == null){
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
                    mediaPlayer.reset();
                    return false;
                }
            });
        }else {
            mediaPlayer.reset();
        }

        try {
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnCompletionListener(onCompletionListener);
            mediaPlayer.setDataSource(soundFile.getAbsolutePath());
            mediaPlayer.prepare();
            mediaPlayer.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /*
    * @function     播放*.ogg格式的音频
    * */
    public static void oggTips(int resourceId){
        mediaPlayer = MediaPlayer.create(MainApplication.application(), resourceId);
        mediaPlayer.start();
    }

    /*
    * @function     暂停音乐
    * */
    public static void pause(){
        if (mediaPlayer != null && mediaPlayer.isPlaying()){
            mediaPlayer.pause();
            isPause = true;
        }
    }

    /*
    * @function     停止音乐
    * */
    public static void stop(){
        if (mediaPlayer != null && mediaPlayer.isPlaying()){
            mediaPlayer.stop();
            isPause = false;
        }
    }

    /*
    * @function     恢复音乐
    * */
    public static void resume(){
        if (mediaPlayer != null && isPause){
            mediaPlayer.start();
            isPause = false;
        }
    }

    /*
    * @function     释放音乐
    * */
    public static void release(){
        if (mediaPlayer != null){
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }
}
